package com.guigu.erp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guigu.erp.dto.StorageGatherDetailsDto;
import com.guigu.erp.mapper.StorageGatherDetailsMapper;
import com.guigu.erp.pojo.StorageCell;
import com.guigu.erp.pojo.StorageGather;
import com.guigu.erp.pojo.StorageGatherDetails;
import com.guigu.erp.service.StorageCellService;
import com.guigu.erp.service.StorageGatherDetailsService;
import com.guigu.erp.service.StorageGatherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

@Service
public class StorageGatherDetailsServiceImpl extends ServiceImpl<StorageGatherDetailsMapper, StorageGatherDetails>
        implements StorageGatherDetailsService {

    @Autowired
    private StorageGatherDetailsService storageGatherDetailsService;

    @Autowired
    private StorageGatherService storageGatherService;

    @Autowired
    private StorageCellService storageCellService;

    @Override
    @Transactional
    public boolean updStorageGatherWithDetail(StorageGatherDetailsDto dto) {
        System.out.println(dto);
        //1.修改入库明细表的确认入库件数  修改入库标志
        dto.setGatherTag("K002-2");
        storageGatherDetailsService.updateById(dto);

        //查询入库设计单的所有已调度的明细
        QueryWrapper<StorageGather> wrapper = new QueryWrapper<>();
        wrapper.eq("GATHER_ID", dto.getGatherId());
        StorageGather serviceOne = storageGatherService.getOne(wrapper);
        QueryWrapper<StorageGatherDetails> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("PARENT_ID", serviceOne.getId());
        queryWrapper.eq("GATHER_TAG", "K002-1");
        List<StorageGatherDetails> list = storageGatherDetailsService.list(queryWrapper);

        //判断明细是否全部调度完
        //2.修改入库表的确认入库总件数 等到所有明细调度完
        if (list.size() == 0) {
            serviceOne.setStoreTag("K002-2");
            serviceOne.setGatheredAmountSum(serviceOne.getAmountSum());
            storageGatherService.updateById(serviceOne);
        }

        //3.修改库存表的当前存储量
        QueryWrapper<StorageCell> cellQueryWrapper = new QueryWrapper<>();
        cellQueryWrapper.eq("PRODUCT_ID", dto.getProductId());
        StorageCell cellServiceOne = storageCellService.getOne(cellQueryWrapper);
        cellServiceOne.setAmount(cellServiceOne.getAmount().add(dto.getGatheredAmount()));
        boolean flag = storageCellService.updateById(cellServiceOne);

        return flag;
    }
}
